const express = require('express');
const Stream = require("node-rtsp-stream");
const fs = require('fs');
const path = require('path');
const bodyParser = require('body-parser')

function writeLog(){
  const count = fs.readFileSync(path.join(__dirname, './err1.txt'), 'utf8');
  fs.writeFileSync('./err1.txt',(Number(count) + 1).toString())
}

// 设置rtsp视频流地址
const rtsp_urls1 = "rtsp://admin:zkhy@123@192.168.8.183:554/Streaming/Channels/102";

function initStream(url,port){
  console.log(url, port)
  try {
    const stream = new Stream({
      name: "sockets1",
      streamUrl: url,
      wsPort: port,
      ffmpegOptions: {
        // 选项ffmpeg标志
        "-stats": "", // 没有必要值的选项使用空字符串
        "-r": 30, // 具有必需值的选项指定键后面的值<br>　　　　'-s':'1920*1080'
        "-fs": 1000000 * 100
      }
    })
    stream.on("novideo", () => {
      console.log("novideonovideonovideonovideonovideooo")
      stream.stop()
      removeVideo(port)
    })
    stream.on('exit', () => {
      try {
        console.log('exitexitexitexitexitexitexitexitexitexit222')
        stream.stop()
        writeLog()
        removeVideo(port)
      } catch (error) {
        console.log('aaaaa',error)
      }
    })
    stream.on('exitWithError', () => {
      stream.stop()
      // writeLog()
      removeVideo(port)
    })
  } catch (error) {
    console.log('err',error)
  }
}

// initStream(rtsp_urls1, 9999)

const app = express()
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*')
  res.header('Access-Control-Allow-Headers', 'Authorization,X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method' )
  res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PATCH, PUT, DELETE')
  res.header('Allow', 'GET, POST, PATCH, OPTIONS, PUT, DELETE')
  next();
})
app.use(bodyParser())
app.listen(5550)


const portList = [9960, 9961, 9962, 9963, 9964, 9965, 9966, 9967, 9968, 9969, 9970, 9971, 9972, 9973, 9974, 9975, 9976, 9977, 9978, 9979,9980, 9981, 9982, 9983, 9984, 9985, 9986, 9987, 9988, 9989, 9990, 9991, 9992, 9993, 9994, 9995, 9996, 9997, 9998, 9999]
const currentStreamList = []
let lastPort = 0
app.post('/showVideo', async (req, res) => {
  const camera = req.body
  const port = checkCamera(camera.ipAddress + '101')
  console.log('pppp',port)
  // res.send({ port })
  if(port){
    const port2 = checkCamera(camera.ipAddress + '201')
    res.send({ port1: port, port2 })
  }else{
    const newPort1 = getPort()
    if(newPort1){
      currentStreamList.push({
        id: camera.ipAddress + '101',
        port: newPort1,
        rtsp_url: `rtsp://${camera.userName}:${camera.password}@${camera.ipAddress}:554/Streaming/Channels/102`,
        stream: initStream(`rtsp://${camera.userName}:${camera.password}@${camera.ipAddress}:554/Streaming/Channels/102`,newPort1)
      })
      console.log(4)
      // rtsp://admin:zkhy@123@192.168.8.183:554/Streaming/Channels/102
      lastPort = newPort1
    }
    const newPort2 = getPort()
    if(newPort2){
      currentStreamList.push({
        id: camera.ipAddress + '201',
        port: newPort2,
        rtsp_url: `rtsp://${camera.userName}:${camera.password}@${camera.ipAddress}:554/Streaming/Channels/202`,
        stream: initStream(`rtsp://${camera.userName}:${camera.password}@${camera.ipAddress}:554/Streaming/Channels/202`,newPort2)
      })
      console.log(4)
      // rtsp://admin:zkhy@123@192.168.8.183:554/Streaming/Channels/102
      lastPort = newPort2
    }
    res.send({ port1: newPort1, port2: newPort2 })
  }
})
function checkCamera(cameraId){
  const stream = currentStreamList.find(stream => stream.id === cameraId)
  console.log('checkCamera',currentStreamList, stream)
  return stream ? stream.port : null
}
function getPort(){
  const currentPortList = currentStreamList.map(stream => stream.port)
  return portList.find(port => !currentPortList.includes(port) && port !== lastPort)
}
function removeVideo(port){
  const index = currentStreamList.findIndex(stream => stream.port === port)
  console.log('removeVideo',currentStreamList, index)
  if(index > -1){
    currentStreamList.splice(index,1)
    console.log('removeVideo222222222222',currentStreamList)
  }
}
